package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.ForumDao;
import com.example.simpleforum.dao.PostDao;
import com.example.simpleforum.dao.ReplyDao;
import com.example.simpleforum.model.Forum;
import com.example.simpleforum.model.Post;
import com.example.simpleforum.model.Reply;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 帖子详情Servlet
 */
public class PostDetailServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取帖子ID
        String postIdStr = request.getParameter("id");
        if (postIdStr == null || postIdStr.trim().isEmpty()) {
            // 帖子ID为空，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
            return;
        }
        
        try {
            int postId = Integer.parseInt(postIdStr);
            
            // 查询帖子详情
            PostDao postDao = new PostDao();
            Post post = postDao.findById(postId);
            
            if (post == null) {
                // 帖子不存在，重定向到帖子列表页面
                response.sendRedirect(request.getContextPath() + "/PostListServlet");
                return;
            }
            
            // 查询帖子的回复列表
            ReplyDao replyDao = new ReplyDao();
            List<Reply> replies = replyDao.findRepliesByPostId(postId);
            
            // 查询帖子所属板块信息
            ForumDao forumDao = new ForumDao();
            Forum forum = forumDao.findById(post.getForumId());
            
            // 将帖子、回复列表和板块信息存入请求属性
            request.setAttribute("post", post);
            request.setAttribute("replies", replies);
            request.setAttribute("forum", forum);
            
            // 转发到帖子详情页面
            request.getRequestDispatcher("/postDetail.jsp").forward(request, response);
        } catch (NumberFormatException e) {
            // 帖子ID格式错误，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // POST请求也执行相同操作
        doGet(request, response);
    }
}